const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class PlanService extends Service {
  /**
   * 培养计划
   * @return {Array} *
   */
  async table() { // !性质,    学期,备注？未处理
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/eams/myPlan!innerIndex.action?projectId=1&_=1713681596702`
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
    })
    // console.log('res.data', res.data.toString());
    const header = ['课程名称', '属性', '性质？', '学分', '周学时', '学时', '开课院系'] // 列名称

    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#planInfoTable7223')
        // const columnNeed = [ 3, 8, -1, 5, 7, 6, 4 ]; // 需要提取的列序号
        const columnNeed = [3, 17, 7, 16, 4, 18] // 需要提取的列序号
        const columnNeed2 = [8, 9, 10, 11, 12, 13, 14, 15] // 需要提取的学期列序号
        const info = {}

        for (let i = 2; i < tableList.length - 3; i++) {
          // const x = [];
          // columnNeed2.forEach(idx => {
          //   // console.log('idx', idx);
          //   x.push(tableList[i][idx] || '');

          // });
          // // console.log('x', x);
          // let term = 8;
          // x.forEach((value, index) => {
          //   if (value === '√') {
          //     term = index;
          //     // return;
          //   }
          // });
          let term = 8
          for (const idx of columnNeed2) {
            const value = tableList[i][idx] || '' // 获取当前行的当前列的值
            if (value === '√') {
              term = idx - 7
              break
            }
          }
          // console.log('term', term);
          if ((term in info) === false) { info[term] = [] }
          const tem = []
          columnNeed.forEach((idx) => {
            // if (idx === -1) tem.push(typeId[tableList[i][2]] || '');
            // else tem.push(tableList[i][idx] || '');
            if (idx === 17) {
              tem.push((tableList[i][idx] || '') === '是' ? '必修' : '选修')
            }
            else {
              tem.push(tableList[i][idx] || '')
              // console.log('tableList[i][1]', tableList[i][1]);
              // console.log('tableList.length', tableList.length);
              // const A = (tableList[i][1] !== '' ? tableList[i][1] : tableList[i][0]);
              // console.log('A', A);
              // console.log('1', 1);
              // tem.splice(2, 0, tableList[i][1] !== '' ? tableList[i][1] : tableList[i][0]);
            }
          })
          info[term].push(tem)
        }
        return { table: info, header }
      } catch (err) {
        return err
      }
    }
    return { table: {}, header }
  }
}
